package com.pn.filter;

import com.alibaba.fastjson.JSON;
import com.pn.entity.Result;
import com.pn.utils.WarehouseConstants;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @WebFilter("/*") // 过滤所有请求
 * 从Servlet 3.0开始，可以使用注解来注册过滤器。只需在过滤器类上添加@WebFilter注解即可。
 *
 * <dependency>
 *     <groupId>javax.servlet</groupId>
 *     <artifactId>javax.servlet-api</artifactId>
 *     <version>3.1.0</version> <!-- Servlet 3.1 是对 3.0 的向后兼容版本 -->
 *     <scope>provided</scope>
 * </dependency>
 */

public class LoginCheckFilter implements Filter {

    private StringRedisTemplate stringRedisTemplate;

    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //过滤器拦截到请求执行的方法
    @Override
    public void doFilter(ServletRequest reqt, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) reqt;
        HttpServletResponse response = (HttpServletResponse) resp;

        /**
         * 1、白名单请求直接放行
         */
        //创建list存放白名单接口
        List<String> urlList = new ArrayList<>();
        urlList.add("/captcha/captchaImage");
        urlList.add("/login");
        urlList.add("/logout");
        urlList.add("/product/img-upload");
        //过滤器拦截到的请求接口
        String url = request.getServletPath();
        if(urlList.contains(url)||url.contains("/img/upload")){//白名单请求
            filterChain.doFilter(request,response);
            return;
        }

        //2、其他请求都校验是否携带token，以及判断redis中是都存在token的键
        String token = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //1）有，说明已经登录，请求放行
        if(StringUtils.hasText(token) && stringRedisTemplate.hasKey(token)){
            filterChain.doFilter(request,response);
            return;
        }
        //2）没有，说明未登录或者token过期，请求不放行，并给前端做出响应
        Result result = Result.err(Result.CODE_ERR_UNLOGINED,"用户未登录！");
        String jsonString = JSON.toJSONString(result);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(jsonString);
        out.flush();
        out.close();
    }
}
